package net.jsoft.platform.core.config.jpa;

import java.util.Properties;

import javax.annotation.Resource;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;

@Configuration
@EnableJpaRepositories(entityManagerFactoryRef = "mysqlEntityManagerFactory", transactionManagerRef = "mysqlTransactionManager", basePackages =
{ "net.jsoft" })
public class JpaPrimaryConfig
{
    @Resource(name = "mysqlDS")
    private DataSource ds;

    @Bean(name = "mysqlEntityManagerFactory")
    @Autowired
    @Qualifier("mysqlDS")
//    @Primary
    public EntityManagerFactory entityManagerFactory(DataSource datasource)
    {
        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        vendorAdapter.setGenerateDdl(true);
        vendorAdapter.setShowSql(true);
        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setJpaVendorAdapter(vendorAdapter);
        factory.setDataSource(datasource);
        factory.setPackagesToScan("net.jsoft");
        Properties jpaProperties = new Properties();
        jpaProperties.put("hibernate.ejb.naming_strategy", "org.hibernate.cfg.ImprovedNamingStrategy");// 命名策略
//        jpaProperties.put("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");// 命名策略
        factory.setJpaProperties(jpaProperties);
        factory.afterPropertiesSet();
        return factory.getObject();

    }

    @Bean(name = "mysqlTransactionManager")
    @Primary
    public PlatformTransactionManager transactionManagerSecondary()
    {
        JpaTransactionManager txManager = new JpaTransactionManager();
        txManager.setEntityManagerFactory(entityManagerFactory(ds));
        return txManager;
    }

    @Bean(name = "mysqlJdbcTemplate")
    public JdbcTemplate mysqlJdbcTemplate(@Qualifier("mysqlDS") DataSource dataSource)
    {

        return new JdbcTemplate(dataSource);

    }

}